package au.com.carboncycle.gb.engine.entities;

import java.awt.Image;
import java.awt.Point;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.util.Arrays;
import java.util.EnumSet;

import org.apache.log4j.Logger;

import au.com.carboncycle.gb.engine.GameClock;
import au.com.carboncycle.gb.engine.resources.Art;

public class BadGuySprite extends Sprite {

	private final static int MOVE_SPEED = 3;
	private static final Logger log = Logger.getLogger(BadGuySprite.class);
	
	private enum BadGuyState {
		MOVING_LEFT,
		MOVING_RIGHT,
		FOLLOWING_HERO,
		
		APPEARING,
		DYING
	}
	
	private final EnumSet<BadGuyState> badGuyState;
	private final WorldEntity world;
	
	
	public BadGuySprite(Point initialPosition, WorldEntity world) {
		super(Art.badGuyRight, Art.badGuyLeft, 0, initialPosition);
		this.badGuyState = EnumSet.of(BadGuyState.APPEARING);
		this.world = world;
	}

	@Override
	protected Image[][] getCurrentSheet() {
		return sheetLeftFacing;
	}

	/**
	 * Perform some elementary AI on the bad guy.
	 * @param gameClock
	 */
	public void tick(GameClock gameClock) {
		if (badGuyState.contains(BadGuyState.APPEARING)) {
			//make bad guy follow hero
			badGuyState.remove(BadGuyState.APPEARING);
			badGuyState.add(BadGuyState.FOLLOWING_HERO);
		}
		
		if (badGuyState.contains(BadGuyState.FOLLOWING_HERO)) {
			Path2D pathToHero = world.getPathToHeroFrom(this);
			PathIterator pathIterator = pathToHero.getPathIterator(null, 0.5);
			double[] coords = new double[6];
			pathIterator.next();
			if (!pathIterator.isDone()) {
				pathIterator.currentSegment(coords);
				double startX = position.getX();
				double startY = position.getY();
				int diffX = (int)( startX - coords[0]);
				int diffY = (int)( startY - coords[1]);
				int deltaX = (diffX % MOVE_SPEED) == 0 ? MOVE_SPEED : (diffX % MOVE_SPEED);
				int deltaY = diffY % MOVE_SPEED;
				move(new Point( (coords[0] < startX) ? -1 * deltaX : deltaX, (coords[1] < startY ? -1 * deltaY : deltaY)));
			}
		}
		
		
		
		
		
		
	}
	
	
	protected void move(Point delta) {
		if (log.isTraceEnabled()) {
			log.trace(delta);
		}
		Point newPosition = new Point(position);
		newPosition.translate(delta.x, delta.y);
		
		if (world.badGuyPositionAllowed(calculateNewBoundsForMoveTo(newPosition), this)) {
			this.position = newPosition;
		}
		
	}
	
	
	
}
